package com.yue92.datalife.controller.v1;

import com.yue92.datalife.helper.UserHelper;
import com.yue92.datalife.model.User;
import com.yue92.datalife.request.UserLoginReq;
import com.yue92.datalife.response.ResponseResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;

import static com.yue92.datalife.common.Constant.CURRENT_USER_ATTRIBUTE;

@RestController
@RequestMapping(value = "/api/v1/users", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class UserController {

    @Autowired
    private UserHelper userHelper;

    @PostMapping("/login")
    public ResponseResource<?> login(@Valid @RequestBody UserLoginReq userLoginReq) {
        String token = userHelper.login(userLoginReq.getEmail(), userLoginReq.getPassword());

        return ResponseResource.success(new HashMap<String, Object>(){{
            put("token", token);
        }});
    }

    @PostMapping("/logout")
    public ResponseResource<?> logout(@RequestAttribute(CURRENT_USER_ATTRIBUTE) User currentUser) {
        userHelper.logout(currentUser);

        return ResponseResource.success(null);
    }

}
